package com.harmontronics.app.pedestal.bridge;

import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.harmontronics.app.pedestal.AppConstants;
import com.harmontronics.app.pedestal.agent.WebActivity;
import com.harmontronics.app.pedestal.bridge.model.BaseBridge;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.json.JSONObject;

import java.io.File;

import wendu.dsbridge.CompletionHandler;

public class NativeBridge extends BaseBridge {

    private LoadingDialog mLoadingDialog;

    private WebActivity activity;

    public NativeBridge(WebActivity activity) {
        this.activity = activity;
    }

    @JavascriptInterface
    public void toolbarController(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("NATIVE.toolbarController");
        if (null == argsJson) {
            handler.complete(fail("参数不能为空", null));
            return;
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
            if (!args.has("show")) {
                throw new IllegalArgumentException("控制参数不能为空");
            }
            boolean show = args.getBoolean("show");
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    activity.showOrHideToolbar(show);
                }
            });

        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }

    @JavascriptInterface
    public String getVersionSync(Object args) {
        LogUtils.d("NATIVE.getVersionSync");
        return success(AppUtils.getAppVersionCode());
    }

    @JavascriptInterface
    public void getVersion(Object args, CompletionHandler<String> handler) {
        LogUtils.d("NATIVE.getVersion");
        handler.complete(success(AppUtils.getAppVersionCode()));
    }

    @JavascriptInterface
    public void update(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("NATIVE.update");
        if (null == argsJson) {
            handler.complete(fail("参数不能为空", null));
            return;
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
            if (!args.has("path")) {
                throw new IllegalArgumentException("基座下载路径不能为空");
            }
            String path = args.getString("path");
            if (TextUtils.isEmpty(path)) {
                throw new IllegalArgumentException("基座下载地址不能为空");
            }

            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (null == mLoadingDialog) {
                        mLoadingDialog = new LoadingDialog(ActivityUtils.getTopActivity());
                    }
                }
            });

            OkGo.<File>get(path)
                    .tag(AppConstants.DOWNLOAD_APK_TAG)
                    .execute(new FileCallback() {
                        @Override
                        public void onStart(Request<File, ? extends Request> request) {
                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mLoadingDialog.setLoadingText("更新中")
                                            .setSuccessText("更新成功")
                                            .setFailedText("更新失败")
                                            .closeFailedAnim()
                                            .closeSuccessAnim()
                                            .show();
                                }
                            });
                        }

                        @Override
                        public void onSuccess(Response<File> response) {
                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mLoadingDialog.loadSuccess();
                                }
                            });

                            AppUtils.installApp(response.body());
                            handler.complete(success("native update success"));
                        }

                        @Override
                        public void onError(Response<File> response) {
                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mLoadingDialog.loadFailed();
                                }
                            });
                            handler.complete(fail("更新失败", response.getException()));
                        }

                        @Override
                        public void downloadProgress(Progress progress) {

                        }
                    });
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }
}
